package com.itheima.wisdomnext.service.ImpI;

import com.itheima.wisdomnext.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {

    private final String imageDir = "D:/浮岛/wisdom-next/src/main/resources/static/uploaded_images";  // 图片保存路径
    private final String videoDir = "D:/浮岛/wisdom-next/src/main/resources/static/uploaded_video";  // 视频保存路径

    @Override
    public String saveFile(MultipartFile file, String type) {
        String fileName = file.getOriginalFilename();
        String fileExtension = getFileExtension(fileName);

        String dir = (type.equals("video")) ? videoDir : imageDir;

        try {
            // 创建目录
            File dirPath = new File(dir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();  // 如果目录不存在，创建目录
            }

            // 保存文件
            File dest = new File(dirPath, fileName);
            file.transferTo(dest);  // 将文件保存到指定目录

            // 返回文件的绝对路径
            return dest.getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
    }
}
